<template>
  <Card :title="title" :loading="loading">
    <div ref="chartRef" :style="{ width, height }"></div>
  </Card>
</template>
<script lang="ts" setup>
  import { Ref, ref, watch } from 'vue'
  import { Card } from 'ant-design-vue'
  import { useECharts } from '/@/hooks/web/useECharts'
  import { useI18n } from '/@/hooks/web/useI18n'
  const { t } = useI18n()

  const props = defineProps({
    title: String,
    loading: Boolean,
    pieData: Object,
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: '300px',
    },
  })
  const chartRef = ref<HTMLDivElement | null>(null)
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>)

  const pieEchartOptions: any = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      bottom: '1%',
      left: 'center',
    },
    series: [
      {
        color: ['#5ab1ef', '#b6a2de', '#67e0e3', '#2ec7c9'],
        name: props.title,
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '12',
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: 0, name: t('routes.dailyTask.piePanel.sleepTime') },
          { value: 0, name: t('routes.dailyTask.piePanel.timeLeft') },
        ],
        animationType: 'scale',
        animationEasing: 'exponentialInOut',
        animationDelay: function () {
          return Math.random() * 100
        },
      },
    ],
  }

  watch(
    () => props.loading,
    () => {
      if (props.loading) {
        return
      }

      setOptions(Object.assign(pieEchartOptions))
    },
    { immediate: true },
  )
  watch(
    () => props.pieData,
    (val) => {
      if (val) {
        setOptions(
          Object.assign(pieEchartOptions, {
            series: [
              Object.assign(pieEchartOptions.series[0], {
                data: [
                  {
                    value: val.currentValue,
                    name: t('routes.dailyTask.piePanel.sleepTime'),
                  },
                  {
                    value: val.targetValue - val.currentValue,
                    name: t('routes.dailyTask.piePanel.timeLeft'),
                  },
                ],
              }),
            ],
          }),
        )
      }
    },
    { deep: true },
  )
</script>
